package com.broadsword.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class LocalTimeConverter implements Converter<LocalTime> {
    private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
    private static final DateTimeFormatter SHORT_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");

    @Override
    public Class<LocalTime> supportJavaTypeKey() {
        return LocalTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (CellDataTypeEnum.NUMBER.equals(cellData.getType()) && cellData.getNumberValue() != null){
            // Excel时间数值是24小时制的小数(0.0=00:00:00, 0.5=12:00:00)
            long totalSeconds =  cellData.getNumberValue().multiply(BigDecimal.valueOf(24)).multiply(BigDecimal.valueOf(60)).multiply(BigDecimal.valueOf(60)).setScale(2, RoundingMode.HALF_UP).longValue();
            return LocalTime.ofSecondOfDay(totalSeconds);
        }else if (CellDataTypeEnum.STRING.equals(cellData.getType()) && cellData.getStringValue() != null){
            try {
                return LocalTime.parse(cellData.getStringValue(), DEFAULT_FORMATTER);
            } catch (DateTimeParseException e1) {
                try {
                    return LocalTime.parse(cellData.getStringValue(), SHORT_FORMATTER);
                } catch (DateTimeParseException e2) {
                    throw new IllegalArgumentException("时间格式应为HH:mm或HH:mm:ss");
                }
            }
        }
        return null;

    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(DEFAULT_FORMATTER.format(value));
    }
}